package com.qycloud.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * redis秒杀主程序
 *
 */
public class RedisMS {
    public static void main(String[] args) {
        Jedis jedis = RedisUtil.getJedis();

        // 预购清单
        String[] arr = { "iphone", "pc", "surface", "mi", "huawei" };
        assignment(arr,10,jedis);

        panicBuying(arr,10,jedis);
    }
    /**
     * 为Redis数据库中的商品赋值
     *
     * @param arr
     *            String 抢购商品数组
     * @param num
     *            int 商品库存
     */
    private static void assignment(String[] arr, int num, Jedis jedis) {

        // 获得连接
        boolean flag = false;

        for (int i = 0; i < arr.length; i++) {
            jedis.set(arr[i], num + "");
        }


    }
    /**
     * 抢购开始
     */
    private static void panicBuying(String[] arr,int threadnum,Jedis jedis){
        //线程池
        ExecutorService fixThreadPool= Executors.newFixedThreadPool(threadnum);
        Random random=new Random();
        for(int i=0;i<threadnum;i++){
            //为线成随机传递需要抢购的商品
            int index=random.nextInt(5);
            RedisThread redisThread = new RedisThread(arr[index], jedis);
            fixThreadPool.submit(redisThread);


        }

    }




}
